<?php

namespace App\Repositories\Ca;

use App\Excel\ExportHandler;
use App\Excel\XlsWriter;
use App\Exceptions\SysException;
use App\Facade\AppContext;
use App\Models\BaseModel;
use App\Models\Ca\Customer;
use App\Models\Ca\CustomerDisease;
use App\Models\Ca\CustomerExtend;
use App\Models\Ca\CustomerLog;
use App\Models\Ca\Disease;
use App\Models\Ca\Docker;
use App\Models\Ca\HandoverRecord;
use App\Models\Ca\Visit;
use App\Models\System\Department;
use App\Models\System\Group;
use App\Repositories\BaseRepository;
use App\Repositories\SaveManyHandler;
use App\Repositories\System\AreaRepository;
use App\Repositories\System\UserRepository;
use App\Utils\Output;
use App\Utils\QueryHelper;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Throwable;

class CustomerRepository extends BaseRepository
{
    /**
     * 分页查询
     * @param array $params
     */
    function adminPager(array $params)
    {
        extract($params);
        $query = Customer::query()->where('ca__customers.hospital_id', '=', AppContext::hospitalId());
        if (!empty($custom_service_id)) {
            $query->where('ca__customers.custom_service_id', '=', $custom_service_id);
        }

        if (!empty($source_id)) {
            $query->where('ca__customers.source_id', '=', $source_id);
        }

        if (!empty($consultation_way_id)) {
            $query->where('ca__customers.consultation_way_id', '=', $consultation_way_id);
        }

        if (!empty($yy_doctor_id)) {
            $query->where('ca__customers.yy_doctor_id', '=', $yy_doctor_id);
        }

        if (!empty($consultation_type)) {
            $query->where('ca__customers.consultation_type', '=', $consultation_type);
        }

        if (!empty($medical_id)) {
            $query->where('ca__customers.medical_id', '=', $medical_id);
        }

        if (!empty($department_id)) {
            if (!empty($disease_id)) {
                //具体的疾病
                $query->whereHas('diseases', function ($query) use ($disease_id) {
                    $query->where('disease_id', '=', $disease_id);
                });
            } else {
                //科室
                $query->whereHas('diseases', function ($query) use ($department_id) {
                    $disease = Disease::find($department_id);
                    $query->join('ca__diseases', 'ca__diseases.id', '=', 'ca__customer_diseases.disease_id');
                    $query->where('ca__diseases.code', 'like', $disease['code'] . '%');
                });
            }
        }

        if (!empty($is_work_today)) {
            $query->where('ca__customers.is_work_today', '=', true);
        }

        if (!empty($is_public)) {
            $query->where('ca__customers.is_public', '=', true);
        }
        if (!empty($effective)) {
            $query->where('ca__customers.effective', '=', $effective);
        }
        if (!empty($status)) {
            $query->where('ca__customers.status', '=', $status);
        }

        if (!empty($keyword)) {
            QueryHelper::like($query, 'ca__customers.name|ca__customers.mobile|ca__customers.id|ca__customers.weixin', $keyword);
        }

        if (!empty($age_range)) {
            if ($age_range == 1) {
                $query->where('ca__customers.age', '<', 12);
            } elseif ($age_range == 2) {
                $query->whereBetween('ca__customers.age', [12, 18]);
            } elseif ($age_range == 2) {
                $query->where('ca__customers.age', '>', 18);
            }
        }

        if (!empty($order_by)) {
            if ($order_by == 1) {
                $query->orderByDesc('ca__customers.yy_time');
            }
        }

        if (!empty($date_range)) {
            $date_type = Arr::get($params, 'date_type', 1);
            list($start, $end) = explode(' ~ ', $date_range);
            if ($date_type == 1) {
                $query->whereBetween('ca__customers.created_at', [$start, $end . ' 23:59:59']);
            } elseif ($date_type == 2) {
                $query->whereBetween('ca__customers.tady_yy_time', [$start, $end . ' 23:59:59']);
            } elseif ($date_type == 3) {
                $query->whereBetween('ca__customers.yy_time', [$start, $end . ' 23:59:59']);
            } elseif ($date_type == 4) {
                $query->whereBetween('ca__customers.jz_time', [$start, $end . ' 23:59:59']);
            }
        }


        $query->leftJoin('system__areas as province', 'province.id', '=', 'ca__customers.province_id');
        $query->leftJoin('system__areas as city', 'city.id', '=', 'ca__customers.city_id');
        $query->leftJoin('ca__dockers as docker', 'docker.id', '=', 'ca__customers.yy_doctor_id');
        $query->leftJoin('ca__sources as source', 'source.id', '=', 'ca__customers.source_id');
        $query->leftJoin('system__users as custom_service', 'custom_service.id', '=', 'ca__customers.custom_service_id');
        $query->leftJoin('system__users as medical', 'medical.id', '=', 'ca__customers.medical_id');
        //权限
        if (AppContext::groupCode() == Group::CALLER) {
            if (AppContext::can('ca/customer', 'can_department') && AppContext::userInfo('department_id') > 0) {
                //查看子部门数据
                $query->leftJoin('system__departments as medical_department', 'medical_department.id', '=', 'medical.department_id');
                $department = Department::find(AppContext::userInfo('department_id'));
                $query->where('medical_department.code', 'like', $department['code'] . '%');
            } else {
                $query->where('ca__customers.medical_id', '=', AppContext::userId());
            }

        } elseif (AppContext::groupCode() == Group::CUSTOM_SERVICE) {
            if (AppContext::can('ca/customer', 'can_department') && AppContext::userInfo('department_id') > 0) {
                //查看子部门数据
                $query->leftJoin('system__departments as cs_department', 'cs_department.id', '=', 'custom_service.department_id');
                $department = Department::find(AppContext::userInfo('department_id'));
                $query->where('cs_department.code', 'like', $department['code'] . '%');
            } else {
                $query->where('ca__customers.custom_service_id', '=', AppContext::userId());
            }
        }

        $query->select(
            'ca__customers.id',
            'ca__customers.name',
            'ca__customers.real_name',
            'ca__customers.age',
            'ca__customers.gender as gender_text',
            'ca__customers.mobile',
            'ca__customers.weixin',
            'ca__customers.consultation_type as consultation_type_text',
            'ca__customers.stage as stage_text',
            'province.name as province_name',
            'city.name as city_name',
            'docker.name as doctor_name',
            'source.name as source_name',
            'custom_service.name as custom_service_name',
            'ca__customers.created_at',
            'ca__customers.tady_yy_time',
            'ca__customers.yy_time',
            'ca__customers.source_id',
            'ca__customers.medical_id',
            'ca__customers.custom_service_id',
            'ca__customers.jz_time',
            'ca__customers.status',
            'ca__customers.status as status_text',
            'ca__customers.yy_doctor_id',
            'ca__customers.cost_money',
            'ca__customers.source_site',
            'ca__customers.source_ip',
            'ca__customers.source_consulting_page',
            'ca__customers.gm_words',
            'ca__customers.is_spend',
            'medical.name as medical_name',
            'ca__customers.effective',
            'ca__customers.last_visit_time',
            'ca__customers.effective as effective_text',
            'ca__customers.source_search_keywords'
        );

        if (!empty($order_field)) {
            $query->orderBy($order_field);
        }
        $query->orderByDesc('id');
        $view_type = Arr::get($params, 'view_type', 'default');
        if ($view_type == 'export') {
            set_time_limit(0);
            ini_set('memory_limit', '2048M');
            $titles = [
                '预约号',
                '姓名',
                '性别',
                '年龄',
                '电话(微信)',
                '诊疗病种',
                '状态',
                '区域',
                '话务员',
                '来源',
                '咨询员',
                '登记时间',
                '预约时间',
                '预约到院时间',
                '到院时间',
                '签到',
                '回访',
                '关键词'
            ];
            $data = [];
            $rows = $query->get();
            $extendMany = CustomerExtend::getMany();
            foreach ($rows as $row) {
                $extendMany->add($row['id']);
            }
            $extendMany->query(['id', 'disease_data', 'visit_data']);
            foreach ($rows as $customer) {
                $_disease_data = [];
                $extend = $extendMany->getByKey($customer['id']);
                if (!empty($extend)) {
                    $customer['disease_data'] = $extend['disease_data'];
                    $customer['visit_data'] = $extend['visit_data'];
                } else {
                    $customer['disease_data'] = [];
                    $customer['visit_data'] = [];
                }
                if (!empty($customer['disease_data'])) {
                    foreach ($customer['disease_data'] as $disease)
                        $_disease_data[] = $disease['name'];
                }
                if ($customer['status'] == 3) {
                    if ($customer['yy_time'] < date('Y-m-d')) {
                        $customer['status'] = 4;
                    }
                }

                $data[] = [
                    $customer['id'],
                    $customer['name'],
                    $customer['gender_text'],
                    empty($customer['age']) ? '无' : $customer['age'],
                    $customer['mobile'] . '(' . $customer['weixin'] . ')',
                    implode('、', $_disease_data),
                    $customer['consultation_type_text'],
                    $customer['province_name'] . ' ' . $customer['city_name'],
                    empty($customer['medical_id']) ? '无' : $customer['medical_name'],
                    empty($customer['source_id']) ? '无' : $customer['source_name'],
                    empty($customer['custom_service_id']) ? '无' : $customer['custom_service_name'],
                    $customer['created_at'],
                    empty($customer['tady_yy_time']) ? '无' : $customer['tady_yy_time'],
                    empty($customer['yy_time']) ? '无' : $customer['yy_time'],
                    empty($customer['jz_time']) ? '无' : $customer['jz_time'],
                    $customer['status_text'],
                    empty($customer['visit_data']) ? 0 : count($customer['visit_data']),
                    empty($customer['source_search_keywords']) ? '无' : $customer['source_search_keywords'],
                ];
            }

            return ExportHandler::get($data, $titles)->download(date('Ymd') . '.xlsx');
        }
        $lis = $query->paginate();
        $extendMany = CustomerExtend::getMany();
        foreach ($lis as $row) {
            $extendMany->add($row['id']);
        }
        $extendMany->query(['id', 'disease_data', 'visit_data', 'disease_desc']);
        foreach ($lis as $row) {
            $extend = $extendMany->getByKey($row['id']);
            if (!empty($extend)) {
                $row['disease_data'] = $extend['disease_data'];
                $row['visit_data'] = $extend['visit_data'];
                $row['disease_desc'] = $extend['disease_desc'];
            } else {
                $row['disease_data'] = [];
                $row['visit_data'] = [];
                $row['disease_desc'] = '';
            }
        }
        return $lis;

    }

    /**
     * 公海
     * @param array $params
     * @return Output
     */
    function publicPager(array $params)
    {
        extract($params);
        $query = Customer::query()->where('ca__customers.hospital_id', '=', AppContext::hospitalId());
        if (!empty($is_public)) {
            $query->where('ca__customers.is_public', '=', true);
        }

        if (!empty($is_public_mobile)) {
            $query->where('ca__customers.medical_id', '=', 0);
        }

        $query->leftJoin('system__areas as province', 'province.id', '=', 'ca__customers.province_id');
        $query->leftJoin('system__areas as city', 'city.id', '=', 'ca__customers.city_id');
        $query->leftJoin('ca__sources as source', 'source.id', '=', 'ca__customers.source_id');
        $query->leftJoin('system__users as custom_service', 'custom_service.id', '=', 'ca__customers.custom_service_id');
        $query->select(
            'ca__customers.id',//预约号
            'ca__customers.name',//姓名
            'ca__customers.mobile',
            'ca__customers.weixin',
            'ca__customers.age',//年龄
            'ca__customers.gender as gender_text',//性别
            'province.name as province_name',//区域
            'city.name as city_name',//区域
            'source.name as source_name',//来源
            'custom_service.name as custom_service_name',//咨询员
            'ca__customers.created_at',//登记时间
            'ca__customers.tady_yy_time',//预约时间
            'ca__customers.yy_time',//预约到院时间
            'ca__customers.jz_time',//到院时间
            'ca__customers.status',
            'ca__customers.status as status_text',
            'ca__customers.source_search_keywords'
        );
        $totalQuery = clone $query;
        $total = $totalQuery->count();
        $lis = $this->setParams($query, $params, ['id' => 'desc']);
        $extendMany = CustomerExtend::getMany();
        foreach ($lis as $li) {
            $extendMany->add($li['id']);
        }
        $extendMany->query(['id', 'disease_data']);
        foreach ($lis as $item) {
            $item['area_name'] = $item['province_name'] . ' ' . $item['city_name'];
            $item['mobile'] = $item['mobile_encryption'] . '(' . $item['weixin'] . ')';
            $extend = $extendMany->getByKey($li['id']);
            $item['disease_data'] = Arr::get($extend, 'disease_data', []);
            $diseases = [];
            foreach ($item['disease_data'] as $datum) {
                $diseases[] = $datum['name'];
            }
            $item['diseases'] = implode('、', $diseases);
            $item['age'] = empty($item['age']) ? '无' : $item['age'];
        }
        return Output::pager($lis, $total);
    }

    public function searchRepeat($kw)
    {
        $query = Customer::query()->where('ca__customers.hospital_id', '=', AppContext::hospitalId());

        if (!empty($kw)) {
            QueryHelper::like($query, 'ca__customers.name|ca__customers.mobile|ca__customers.id|ca__customers.weixin', $kw);
            $query->leftJoin('system__users as custom_service', 'custom_service.id', '=', 'ca__customers.custom_service_id');
            $query->select(
                'ca__customers.id',
                'ca__customers.name',
                'ca__customers.age',
                'ca__customers.created_at',
                'ca__customers.status',
                'custom_service.name as custom_service_name',
                'ca__customers.status as status_text',
            );
            $extendMany = CustomerExtend::getMany();
            $lis = $query->get();
            foreach ($lis as $li) {
                $extendMany->add($li['id']);
            }
            $extendMany->query(['id', 'visit_data', 'swt']);
            foreach ($lis as $li) {
                $extend = $extendMany->getByKey($li['id']);
                $li['visit_data'] = Arr::get($extend, 'visit_data', []);
                $li['swt'] = Arr::get($extend, 'swt', '');
            }
            return $lis;
        } else {
            return false;
        }

    }

    public function checkMobile($mobile)
    {
        $count = Customer::query()->where('mobile', '=', $mobile)->where('ca__customers.hospital_id', '=', AppContext::hospitalId())->count();
        return Output::data($count);
    }

    public function checkWeixin($weixin)
    {
        $count = Customer::query()->where('weixin', '=', $weixin)->where('ca__customers.hospital_id', '=', AppContext::hospitalId())->count();
        return Output::data($count);
    }

    public function checkName($name)
    {
        $count = Customer::query()->where('name', '=', $name)->where('ca__customers.hospital_id', '=', AppContext::hospitalId())->count();
        return Output::data($count);
    }

    public function handover($from, $to, $type = 1)
    {
        try {
            DB::beginTransaction();
            $query = Customer::query();
            if ($type == 1) {
                $customers = $query->where('custom_service_id', '=', $from)->get();
            } else {
                $customers = $query->where('medical_id', '=', $from)->get();
            }
            $extendMany = CustomerExtend::getMany();
            $customers = $query->get();
            foreach ($customers as $li) {
                $extendMany->add($li['id']);
            }
            $extendMany->query(['id', 'medical_history',
                'disease_desc',
                'remark',
                'disease_data',
                'visit_data',
                'swt']);
            foreach ($customers as $li) {
                $extend = $extendMany->getByKey($li['id']);
                if (!empty($extend)) {
                    foreach ($extend as $key => $value) {
                        $li[$key] = $value;
                    }
                }
            }


            $logs = [];
            $date = date('Y-m-d H:i:s');
            $ids = [];
            foreach ($customers as $customer) {
                $old = $customer->toSql();
                if ($type == 1) {
                    $customer['custom_service_id'] = $to;
                } else {
                    $customer['medical_id'] = $to;
                }
                $ids[] = $customer['id'];
                $logs[] = [
                    'user_id' => AppContext::userId(),
                    'customer_id' => $customer['customer_id'],
                    'desc' => $type == 1 ? '客服交接' : '话务交接',
                    'type' => CustomerLog::TYPE_HANDOVER_CALLER,
                    'created_at' => $date,
                    'update_at' => $date,
                    'change_data' => json_encode([
                        'old' => $old,
                        'new' => $customer->toArray(),
                    ]),
                ];
            }
            if (count($logs)) {
                $logs = array_chunk($logs, 100);
                foreach ($logs as $log) {
                    CustomerLog::query()->insert($log);
                }
            }
            if ($type == 1) {
                Customer::query()->whereIn('id', $ids)->update([
                    'custom_service_id' => $to
                ]);
            } else {
                Customer::query()->whereIn('id', $ids)->update([
                    'medical_id' => $to
                ]);
            }

            HandoverRecord::create([
                'from_user_id' => $from,
                'to_user_id' => $to,
                'user_id' => AppContext::userId(),
                'type' => $type,
                'data_count' => count($ids),
                'customer_ids' => implode(',', $ids),
            ]);
            DB::commit();
        } catch (Throwable $throwable) {
            DB::rollBack();
            return Output::error($throwable);
        }
        return Output::success();
    }

    public function leaveHospital($id): Output
    {
        return $this->updateCustomer($id, function ($entity) {
            $entity['status'] = 6;
            $entity['cy_time'] = time();
            $entity->save();
            return $entity;
        }, CustomerLog::TYPE_LEAVE_HOSPITAL, '出院');
    }

    public function hospitalization($id): Output
    {
        return $this->updateCustomer($id, function ($entity) {
            $entity['status'] = 5;
            $entity['zy_time'] = time();
            $entity->save();
            return $entity;
        }, CustomerLog::TYPE_HOSPITALIZATION, '到院');
    }

    public function arriving($id, $yy_doctor_id)
    {
        return $this->updateCustomer($id, function ($entity) use ($yy_doctor_id) {
            $entity['status'] = 3;
            $entity['yy_doctor_id'] = $yy_doctor_id;
            $entity['jz_time'] = date('Y-m-d H:i:s');
            $entity['jz_guide_doctor_id'] = AppContext::userId();
            $entity->save();
            return $entity;
        }, CustomerLog::TYPE_ARRIVING, '就诊');
    }

    public function spend($id, $isSpend)
    {
        return $this->updateCustomer($id, function ($entity) use ($isSpend) {
            $entity['spend_time'] = $isSpend ? date('Y-m-d H:i:s') : null;
            $entity['is_spend'] = $isSpend;
            $entity->save();
            return $entity;
        }, CustomerLog::TYPE_ARRIVING, '消费');
    }


    public function onlineArriving($id)
    {
        return $this->updateCustomer($id, function ($entity) {
            $entity['status'] = 6;
            $entity['jz_time'] = date('Y-m-d H:i:s');
            $entity['jz_guide_doctor_id'] = AppContext::userId();
            $entity->save();
            return $entity;
        }, CustomerLog::TYPE_ONLINE_ARRIVING, '线上签到');
    }

    public function loss($id, $reason)
    {
        return $this->updateCustomer($id, function ($entity) use ($reason) {
            $entity['status'] = 4;
            $entity['appointment_loss_reason_data'] = $reason;
            $entity['ls_time'] = time();
            $entity->save();
            return $entity;
        }, CustomerLog::TYPE_LOSS, '流失');
    }

    public function receive($id)
    {
        return $this->updateCustomer($id, function ($entity) {
            if (!$entity['is_public']) {
                throw new SysException('领取失败！有可能被其他人领取了！');
            }
            $entity['is_public'] = false;
            // $entity['custom_service_id'] = AppContext::userId();
            $entity['medical_id'] = AppContext::userId();
            $entity->save();
            return $entity;
        }, CustomerLog::TYPE_RECEIVE, '话务领取');
    }

    public function receiveMedical($id)
    {
        return $this->updateCustomer($id, function ($entity) {
            if (!empty($entity['medical_id'])) {
                throw new SysException('领取失败！有可能被其他人领取了！');
            }
            $entity['medical_id'] = AppContext::userId();
            $entity->save();
            return $entity;
        }, CustomerLog::TYPE_MEDICAL_RECEIVE, '话务领取');
    }

    public function allocation($caller_id, $ids)
    {
        try {
            DB::beginTransaction();
            foreach ($ids as $id) {
                $this->updateCustomer($id, function ($entity) use ($caller_id) {
                    if (!empty($entity['medical_id'])) {
                        throw new SysException('领取失败！有可能被其他人领取了！');
                    }
                    $entity['medical_id'] = $caller_id;
                    $entity->save();
                    return $entity;
                }, CustomerLog::TYPE_MEDICAL_RECEIVE, '话务分配');
            }
            DB::commit();
        } catch (Throwable $throwable) {
            DB::rollBack();
            return Output::error($throwable, '分配报错');
        }
        return Output::success();
    }

    /**
     * 回访
     * @param $id
     * @param $hf_time
     * @param $content
     * @return Output
     */
    public function visit($id, $hf_time, $content)
    {
        return $this->updateCustomer($id, function ($entity) use ($hf_time, $content) {
            Visit::create([
                'hospital_id' => $entity['hospital_id'],
                'customer_id' => $entity['id'],
                'user_id' => AppContext::userId(),
                'content' => $content,
                'next_time' => $hf_time,
            ]);
            $entity['hf_time'] = $hf_time;
            $entity['last_visit_time'] = date('Y-m-d H:i:s');
            $entity['last_visit_user_id'] = AppContext::userId();
            if (!empty($hf_time)) {
                $hf_time = strtotime($hf_time);
                $start = strtotime(date('Y-m-d'));
                $entity['is_work_today'] = $hf_time == $start && $hf_time < ($start + 86400);
            } else {
                $entity['is_work_today'] = false;
            }

            $visit_data = Visit::query()
                ->join('system__users', 'system__users.id', '=', 'ca__visits.user_id')
                ->where('ca__visits.customer_id', '=', $entity['id'])
                ->select('ca__visits.id',
                    'ca__visits.content',
                    'ca__visits.user_id',
                    'ca__visits.next_time',
                    'system__users.name as user_name',
                    'system__users.username as user_username',
                    'system__users.mobile as user_mobile',
                    'ca__visits.created_at'
                )
                ->get()->toArray();
            CustomerExtend::query()->updateOrCreate(['id' => $entity['id']], ['visit_data' => $visit_data]);
            $entity->save();
            return $entity;
        }, CustomerLog::TYPE_VISIT, '回访');
    }


    public function updateCustomer($id, $call, $type, $logDesc): Output
    {
        $entity = Customer::find($id);
        if (empty($entity)) {
            return Output::fail('数据不存在！');
        }
        try {
            DB::beginTransaction();
            $old = $entity->toArray();
            $entity = $call($entity);
            $this->addLog($id, $type, $logDesc, [
                'old' => $old,
                'new' => $entity->toArray(),
            ]);
            DB::commit();
        } catch (Throwable $throwable) {
            DB::rollBack();
            return Output::error($throwable, $logDesc);
        }
        return Output::success();
    }

    /**
     * 保存数据
     * @param array $data 数据数组
     * @param int $id 主键 0 新增
     * @return Output
     */
    function save(array $data, int $id = 0): Output
    {
        $handler = SaveManyHandler::get(CustomerDisease::query(), 'customer_id');
        $handler->setUniqueCall(function ($item) {
            return Arr::get($item, 'disease_id', '');
        });
        $_id = 0;
        if ($id) {
            $model = $this->model::find($id);
            if (empty($model)) {
                return Output::fail(__('common.tips.data_does_not_exist'), $id);
            }
            $extend = CustomerExtend::query()->where('id', '=', $id)->first();
            $old = $model->toArray();
            if (!empty($extend)) {
                $extendOld = $extend->toArray();
                unset($extendOld['created_at'], $extendOld['updated_at']);
                $old = array_merge($old, $extendOld);
            };
            if (!empty($data['yy_time']) && $old['yy_time'] != $data['yy_time']) {
                $data['tady_yy_time'] = date('Y-m-d H:i:s');
            } else {
                $data['yy_time'] = null;
            }
            $model->fill($data)->save();
            if (!empty($extend)) {
                $extend->fill($data)->save();
            } else {
                $data['id'] = $id;
                $extend = CustomerExtend::create($data);
            }
            $extend = $extend->toArray();
            unset($extend['created_at'], $extend['updated_at']);
            $this->addLog($model['id'], CustomerLog::TYPE_UPDATE, '修改', [
                'old' => $old,
                'new' => array_merge($model->toArray(), $extend)
            ]);
            $handler->setForeignId($id);
            $_id = $id;
        } else {

            $data['hospital_id'] = AppContext::hospitalId();
            $data['custom_service_id'] = AppContext::userId();
            if (!empty($weixin)) {
                $count = Customer::query()->where('weixin', '=', $weixin)->where('ca__customers.hospital_id', '=', AppContext::hospitalId())->count();
                if ($count > 0)
                    return Output::fail('微信号已被添加过');
            }
            if (!empty($mobile)) {
                $count = Customer::query()->where('mobile', '=', $mobile)->where('ca__customers.hospital_id', '=', AppContext::hospitalId())->count();
                if ($count > 0)
                    return Output::fail('电话号码已被添加过');
            }


            if (!empty($data['yy_time'])) {
                $data['tady_yy_time'] = date('Y-m-d H:i:s');
            } else {
                $data['yy_time'] = null;
            }
            if (!empty($data['mobile'])) {
                $data['ztype'] = 1;//表示套电数据
            } elseif (!empty($data['weixin'])) {
                $data['ztype'] = 2;//表示套微数据
            }

            $this->model->fill($data)->save();
            $data['id'] = $this->model['id'];
            $extend = CustomerExtend::create($data)->toArray();
            unset($extend['created_at'], $extend['updated_at']);
            $this->addLog($this->model['id'], CustomerLog::TYPE_CREATE, '新增', [
                'new' => array_merge($this->model->toArray(), $extend)
            ]);
            $_id = $this->model['id'];
        }
        $handler->setCommonData([
            'customer_id' => $_id,
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
        ]);
        $handler->setModifyMode(SaveManyHandler::MODIFY_MODE_UPDATE);
        $handler->setAdditionalFields([
            'disease_id',
        ]);
        $diseases = Arr::get($data, 'diseases', []);
        $handler->save($diseases);
        if ($id) {
            return Output::success(__('common.tips.modified_successfully'), $id);
        } else {
            return Output::success(__('common.tips.added_successfully'), $this->model['id']);
        }

    }

    /**
     * 获取对象详情
     * @param int $id
     * @return Output
     */
    function detail(int $id, $isDetail = false)
    {
        try {
            $entity = $this->model->find($id);
            if (!empty($entity)) {
                if ($isDetail) {
                    $entity['gender_text'] = $entity['gender'];
                    $rep = new ConsultationWayRepository();
                    $entity['consultation_way_text'] = $rep->getName($entity['consultation_type']);
                    $entity['status_text'] = $entity['status'];
                    $rep = new DockerRepository();
                    $entity['yy_doctor_name'] = $rep->getName($entity['yy_doctor_id']);

                    $rep = new SourceRepository();
                    $entity['source_name'] = $rep->getName($entity['source_id']);

                    $rep = new UserRepository();
                    $entity['medical_name'] = $rep->getName($entity['medical_id']);

                    $entity['custom_service_name'] = $rep->getName($entity['custom_service_id']);
                    $rep = new AreaRepository();
                    $entity['province_name'] = $rep->getName($entity['province_id']);
                    $entity['city_name'] = $rep->getName($entity['city_id']);

                    $entity['visit_data'] = Visit::query()
                        ->join('system__users', 'system__users.id', '=', 'ca__visits.user_id')
                        ->where('ca__visits.customer_id', '=', $entity['id'])
                        ->select('ca__visits.id',
                            'ca__visits.content',
                            'ca__visits.user_id',
                            'ca__visits.next_time',
                            'ca__visits.supervisor_annotate',
                            'system__users.name as user_name',
                            'system__users.username as user_username',
                            'system__users.mobile as user_mobile',
                            'ca__visits.created_at'
                        )
                        ->get()->toArray();
                }
                $extend = CustomerExtend::query()->where('id', '=', $entity['id'])
                    ->select(
                        'medical_history',
                        'disease_desc',
                        'remark',
                        'disease_data',
                        'visit_data',
                        'swt'
                    )
                    ->first();
                if (!empty($extend)) {
                    $entity = array_merge($entity->toArray(), $extend->toArray());
                }
                return Output::data($entity);
            }
            return Output::fail(__('common.tips.data_does_not_exist'));
        } catch (Throwable $exception) {
            return Output::error($exception, __('common.tips.get_data_exception'));
        }
    }

    public function addLog($id, $type, $desc, $changeData)
    {
        CustomerLog::create([
            'user_id' => AppContext::userId(),
            'customer_id' => $id,
            'desc' => $desc,
            'type' => $type,
            'change_data' => $changeData,
        ]);
    }

    function getModel(): BaseModel
    {
        return new Customer();
    }
}